<?php

/**
 * Storage Class
 * 
 * It can be database or in future to accomodate 
 * NoSQL or other libraries
 *
 */
class storage {
    # singleton instance holder

    public static $storage_instance;
    public static $connection_resource;

    public function __construct() {
        $this->invoke();
    }

    public static function __s() {
        if (!isset(self::$storage_instance)) {
            $className = __CLASS__;
            self::$storage_instance = new $className;
        }
        return self::$storage_instance;
    }

    private function invoke() {
        self::$connection_resource = mysql_connect(STORAGE_HOST, STORAGE_USER, STORAGE_PASS);
        mysql_select_db(STORAGE_DB);
        if (!self::$connection_resource) {
            throw new Exception("Storage Failure. <br />" . mysql_error());
        }
    }

    /**
     * Gets data from query result and formats into array
     * @param type $result query result resource
     * @param type $field optional. group by field1
     * @param type $second_field optional. group by field2
     * @param type $third_field options. group by field3
     * @return type 
     */
    public function format_data($result, $field=NULL, $second_field=NULL, $third_field=NULL) {
        $data_array = array();
        if ($result) {
            while ($array = mysql_fetch_assoc($result)) {
                $t = array();
                foreach ($array as $field_name => $value) {
                    $t[$field_name] = ($value);
                }
                if (isset($field)) {
                    if (isset($second_field)) {
                        if (isset($third_field)) {
                            $data_array[$t[$field]][$t[$second_field]][$t[$third_field]] = $t;
                        } else {
                            $data_array[$t[$field]][$t[$second_field]] = $t;
                        }
                    } else {
                        $data_array[$t[$field]][] = $t;
                    }
                } else {
                    $data_array[] = $t;
                }
            }
        }
        return $data_array;
    }

    public function query($query) {
        $res = mysql_query($query);
        if ($res)
            return $res;
        else {
            throw new Exception("Error during query. <br />" . mysql_error() . "<br />" . $query);
        }
    }
    
    
}

?>
